package com.channel.temperature.collect.ui.activity

import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Observer
import com.hjy.bluetooth.HBluetooth
import com.hjy.bluetooth.entity.BluetoothDevice
import com.hjy.bluetooth.entity.ScanFilter
import com.hjy.bluetooth.inter.ScanCallBack
import com.channel.temperature.collect.R
import com.channel.temperature.collect.app.base.BaseActivity
import com.channel.temperature.collect.app.ext.LiveDataEvent
import com.channel.temperature.collect.data.annotation.ValueKey
import com.channel.temperature.collect.data.response.BLEConnectDevice
import com.channel.temperature.collect.data.response.DeviceInfo
import com.channel.temperature.collect.databinding.ActivityDeviceListBinding
import com.channel.temperature.collect.ui.adapter.DeviceAdapter
import com.channel.temperature.collect.ui.viewmodel.DeviceListModel
import me.hgj.mvvmhelper.ext.divider
import me.hgj.mvvmhelper.ext.getColorExt
import me.hgj.mvvmhelper.ext.grid
import me.hgj.mvvmhelper.ext.setOnclickNoRepeat
import me.hgj.mvvmhelper.util.decoration.DividerOrientation


class DeviceListActivity : BaseActivity<DeviceListModel, ActivityDeviceListBinding>() {
    var isScanOver = false

    var deviceType = 2
    var deviceFilterName = "TZWM23A"

    companion object {
        const val TAG = "DeviceListActivity"
    }

    private val deviceAdapter: DeviceAdapter by lazy { DeviceAdapter() }
    override fun initView(savedInstanceState: Bundle?) {
        mToolbar.setNoToolBar()
        deviceType = intent.getIntExtra(ValueKey.DeviceType, 2)
        deviceFilterName = if (deviceType == 2)
            "TZWM23A"
        else "TZWM23S"
        Log.e(TAG, "扫描类型 " + deviceType);
        //初始化 recycleView
        mBind.listRecyclerView.grid(1).divider {
            orientation = DividerOrientation.GRID
            includeVisible = true
            setDivider(1, true)
            setColor(getColorExt(R.color.common_text_hint_color))
        }.adapter = deviceAdapter
        //1:系统设置界面的经典蓝牙  2：BLE蓝牙 3：任务界面的经典蓝牙
        if (deviceType == 2) {
            scanWithTimeUse(2)
        } else {
            scanWithTimeUse(1)
        }

        deviceAdapter.setOnItemClickListener { adapter, view, position ->
            if (deviceType == 2) {
                LiveDataEvent.connectBleDevice.value =
                    BLEConnectDevice(adapter.data.get(position) as BluetoothDevice, true)
                DeviceListActivity@ this.finish()
            } else if (deviceType == 1) {
                LiveDataEvent.SystemSettingConnectSPPDevice.value =
                    BLEConnectDevice(adapter.data.get(position) as BluetoothDevice, true)
                DeviceListActivity@ this.finish()
            } else if (deviceType == 3) {
                LiveDataEvent.connectSPPDevice.value =
                    BLEConnectDevice(adapter.data.get(position) as BluetoothDevice, true)
                DeviceListActivity@ this.finish()
            } else if (deviceType == 4) {
                LiveDataEvent.OfflineConnectSPPDevice.value =
                    BLEConnectDevice(adapter.data.get(position) as BluetoothDevice, true)
                DeviceListActivity@ this.finish()
            }

        }
    }

    //    override fun initImmersionBar() {
//        Log.e("测试", "测试1111")
//    }
    override fun showToolBar() = false

    /**
     * 请求成功
     */
    override fun onRequestSuccess() {
        mViewModel.listData.observe(this, Observer {

            deviceAdapter.setNewInstance(it.deviceListData)
            deviceAdapter.notifyDataSetChanged()
        })
    }

    override fun onBindViewClick() {
        setOnclickNoRepeat(mBind.btnScan) {
            when (it) {
                mBind.btnScan -> {
                    if (!isScanOver) {
                        mViewModel.clearFounded()
                    } else {
                        mViewModel.clearFounded()
                        if (deviceType == 2) {
                            scanWithTimeUse(2)
                        } else {
                            scanWithTimeUse(1)
                        }
                    }

                }

            }
        }
    }

    private fun scanWithTimeUse(type: Int) {
        isScanOver = false
        Log.e("scanWithTimeUse", "过滤的名字 " + deviceFilterName)
        //扫描蓝牙设备，扫描6秒就自动停止扫描
        HBluetooth.getInstance().scan(
            type,
            10000,
            ScanFilter(true, deviceFilterName),
            object : ScanCallBack {
                override fun onScanStart() {
                    Log.e(TAG, "开始扫描")
                }

                override fun onScanning(
                    scannedDevices: MutableList<BluetoothDevice>?,
                    currentScannedDevice: BluetoothDevice?
                ) {
                    mViewModel.listData.value = scannedDevices?.let { DeviceInfo(it) }

                }

                override fun onError(errorType: Int, errorMsg: String?) {
                    Log.e(TAG, "errorType:" + errorType + "  errorMsg:" + errorMsg);
                }

                override fun onScanFinished(bluetoothDevices: MutableList<BluetoothDevice>?) {
                    Log.e(TAG, "扫描结束")
//                ToastUtils.show("扫描结束")
                    isScanOver = true
                }
            })
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}